
package org.vasil.jouikov.synchro

import javax.servlet.ServletConfig

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.annotation.WebServlet;

@WebServlet("/items")
class ItemsService extends HttpServlet {

    def mongodb = new DatabaseService()

    def void init(ServletConfig config) {
	super.init(config)
    }

    def processRequest = { request, response ->

        def result = new StringBuilder()
        result << "<?xml version='1.0'?>\n"
        result << "<status>\n"
        
        def body = getXML(request)
        //println "body:\n${body.body}"
        result << "  <getxml>OK ${body.time}ms</getxml>\n"

        def xml = parseXmlToMap(body.body)
        result << "  <parsexml>OK: ${xml.body} | ${xml.time}ms</parsexml>\n"

        result << "</status>\n"
        response.setContentType("text/xml;charset=UTF-8")
        response.getWriter().write(result.toString())
    }

    def getXML = { request ->

        def start = System.currentTimeMillis()
        def buf = new StringBuilder()
        try {
            def bytes = new byte[4096]
            def input = request.getInputStream()

            for(int n; (n = input.read(bytes)) != -1; ) {
                buf << new String(bytes, 0, n)
            }
        }
        catch(error) {
            return [status: "ERR", body: error, time: System.currentTimeMillis() - start]
        }

        return [status: "OK", body: new String(buf.toString()), time: System.currentTimeMillis() - start]
    }


    def parseXmlToMap = { xml ->

        def start = System.currentTimeMillis()

        def root
        try {
            root = new XmlSlurper().parseText(xml)
        }
        catch(error) {
            return [status: "ERR", body: error, time: System.currentTimeMillis() - start]
        }

        def res = new StringBuilder()
        if(root.name() == 'items') {
            def map = [:], sku, action, expect

            root.item.each { item ->
                try {
                    sku = item.@accwareid.text()
                    action = item.@action.text()

                    switch(action) {
                        case 'price':
                            println "price sku=${sku}"
                            expect = doPrice(sku, item)
                            break
                        case 'desc':
                            println "desc sku=${sku}"
                            expect = doDescription(sku, item)
                            break
                        case 'delete':
                            println "delete sku=${sku}"
                            expect = doDelete(sku)
                            break
                    }

                    res << "<item sku='${sku}' action='${action}'>Ok: ${expect}</item>"
                }
                catch(e) {
                    res << "<item sku='${sku}' action='${action}'>Error: ${expect} : ${e}</item>"
                }
            }

            return ['status': "OK", body: res.toString(), 'time': System.currentTimeMillis() - start]
        }

        return ['status': 'ERR', 'body': 'Empy xml or tag <items>']
    }

    def doPrice = { sku, item ->
        def start = System.currentTimeMillis()

        return "doPrice: ${System.currentTimeMillis() - start}ms."
    }

    def doDescription = { sku, item ->

        def start = System.currentTimeMillis()

        mongodb.updateCategory(sku, item) // first check category and subcategory
        //parseDescription(sku)
        mongodb.updateItem(sku, item)

        return "doDescription: ${System.currentTimeMillis() - start}ms."
/*
                            def url = "http://10.0.1.93/EditorXML/EtilizeXML.ashx?OPR=10&SKUBM=${attraccwareid}"
                            udesc = url.toURL().text

                            newitems[attraccwareid] =
                                new Item(
                                    category: [
                                        parentid:       item.category.parentid.text(),
                                        parentname:     item.category.parentname.text(),
                                        categoryid:     item.category.categoryid.text(),
                                        catname:        item.category.catname.text(),
                                        prefname1:      clean(item.category.prefname1.text()),
                                        prefname2:      clean(item.category.prefname2.text()),
                                        prefname3:      clean(item.category.prefname3.text()),
                                        prefname4:      clean(item.category.prefname4.text()),
                                        prefname5:      clean(item.category.prefname5.text())
                                    ],
                                    vendor: [
                                        alias:          item.vendor.alias.text(),
                                        name:           clean(item.vendor.name.text())
                                    ],
                                    field: [
                                        costprice:      item.costprice.text() as Double,
                                        sellprice:      item.sellprice.text() as Double,
                                        reslprice:      item.reslprice.text() as Double,
                                        stock:          getYesNo(item.stock),
                                        itemname:       clean(item.itemname.text()),
                                        advname:        setLimitLength(clean(item.advname.text()), 70),
                                        mfrname:        setLimitLength(cleanSpace(item.mfrname.text()), 35),
                                        mfrnumber:      setLimitLength(cleanSpace(item.mfrnumber.text()), 30),
                                        advprice:       getYesNo(item.advprice),
                                        mfrlink:        setLimitLength(item.mfrlink.text().replaceAll(/http:\/\//, '').replaceAll(/https:\/\//, '').replaceAll(/ftp:\/\//, ''), 128),
                                        packinclude:    setLimitLength(clean(item.packinclude.text()), 255),
                                        packcomment:    setLimitLength(clean(item.packcomment.text()), 512),
                                        stockdate:      item.stockdate.text(),
                                        weight:         item.weight.text()     as Double,
                                        reslprice1:     item.reslprice1.text() as Double,
                                        reslprice2:     item.reslprice2.text() as Double,
                                        reslprice3:     item.reslprice3.text() as Double,
                                        reslqty2:       item.reslqty2.text()   as Integer,
                                        reslqty3:       item.reslqty3.text()   as Integer,
                                        drone:          getBoolean(item.drone),
                                        wtymask:        item.wtymask.text()    as Integer,
                                        wtyprice1:      item.wtyprice1.text()  as Double,
                                        wtyprice2:      item.wtyprice2.text()  as Double,
                                        wtyprice3:      item.wtyprice3.text()  as Double,
                                        googlegroup:    item.googlegroup ? setLimitLength(item.googlegroup.text(), 15) : '',
                                        active:         'Y'
                                    ],
                                    quantity: [
                                        qty:            item.qty.text() as Integer
                                    ],
                                    fdesc: [
                                        desc:           udesc,
                                        size:           udesc.length(),
                                        etilid:         0L
                                    ],
                                    pref: [
                                        pref1:          setLimitLength(clean(item.pref1.text()), 30),
                                        pref2:          setLimitLength(clean(item.pref2.text()), 30),
                                        pref3:          setLimitLength(clean(item.pref3.text()), 30),
                                        pref4:          setLimitLength(clean(item.pref4.text()), 30),
                                        pref5:          setLimitLength(clean(item.pref5.text()), 30)
                                    ],
                                    advert: [
                                        advmfrname:     setLimitLength(cleanSpace(item.advmfrname.text()), 35),
                                        advmfrnumber:   setLimitLength(cleanSpace(item.advmfrnumber.text()), 30),
                                        keywords:       clean(item.keywords.text()),
                                        cnet:           getBoolean(item.advert.cnet),
                                        grabber:        getBoolean(item.advert.grabber),
                                        bizrate:        getBoolean(item.advert.bizrate),
                                        nextag:         getBoolean(item.advert.nextag),
                                        shopping:       getBoolean(item.advert.shopping),
                                        powersource:    getBoolean(item.advert.powersource),
                                        froogle:        getBoolean(item.advert.froogle),
                                        cj:             getBoolean(item.banner.cj),
                                        gadgetpage:     getBoolean(item.banner.gadgetpage),
                                        upccode:        setLimitLength(item.upccode.text(), 15)
                                    ],
                                    banner: [
                                        special:        getBoolean(item.banner.special),
                                        closeout:       getBoolean(item.banner.closeout),
                                        comingsoon:     getBoolean(item.banner.comingsoon),
                                        bestprice:      getBoolean(item.banner.bestprice),
                                        firstpage:      getBoolean(item.banner.firstpage),
                                        categorypage:   getBoolean(item.banner.categorypage),
                                        ebay:           getBoolean(item.banner.ebay),
                                        lot:            getBoolean(item.lot)
                                    ],
                                    utils: [
                                        action:         attraction,
                                        accwareid:      attraccwareid,
                                        catid:          0,
                                        vendid:         2, // CVS
                                        itemid:         0
                                    ],
                                    json: [
                                        imgs:           '',
                                        namea:          '',
                                        nameb:          '',
                                        pkeywrd:        '',
                                        pics:           ''
                                    ],
                                    images: [ // images from bookmaker
                                        url0:       item.images.url0.text(),
                                        url1:       item.images.url1.text(),
                                        url2:       item.images.url2.text(),
                                        url3:       item.images.url3.text()
                                    ]
*/
    }

    def doDelete = { sku ->
        def start = System.currentTimeMillis()

        return "doDelete:${System.currentTimeMillis() - start}ms."
    }

    def parseDescription = { sku ->

        def start = System.currentTimeMillis()

        def xml
        try {
            xml = "http://10.0.1.93/EditorXML/EtilizeXML.ashx?OPR=10&SKUBM=${sku}".toURL().text
        }
        catch(e) {
            return ['status': 'ERR', 'body': error]
        }
/*
        def root
        try {
            root = new XmlSlurper().parseText(xml)
        }
        catch(error) {
            return ['status': 'ERR', 'body': error]
        }

        if('EMPTY' == root.D.text()) {
            return ['status': 'ERR', 'body': 'Etilize xml EMPTY']
        }

        nitem.fdesc['etilid'] = root.@PRODETID.text() as Long
        nitem.json['namea']   = root.NAMEA.text()
        nitem.json['nameb']   = root.NAMEB.text()
        nitem.json['minfo']   = root.MINFO.text()
        nitem.json['psiml']   = root.PSIML.D.text()
        nitem.json['paccl']   = root.PACCL.D.text()
        nitem.json['pkeywrd'] = root.PKEYWRD.text()

        def mspec = new StringBuilder(), idx = 0
        mspec << "name:\"\",attr:{"
        root.MSPEC.S.M.each { m ->
            mspec << (idx++ ? ',' : '') << "\"${clean(m.L.text())}\":\"${clean(m.D.text())}\""
        }
        mspec << "}"
        nitem.json['mspec'] = mspec

        def espec = new StringBuilder(), idy = 0
        root.ESPEC.S.each { s ->
            espec << (idy++ ? ',' : '') << "{name:\"${clean(s.T.text())}\",attr:{"
            idx = 0
            s.M.each { m ->
                espec << (idx++ ? ',' : '') << "\"${clean(m.L.text())}\":\"${clean(m.D.text())}\""
            }
            espec << "}}"
        }
        nitem.json['espec'] = espec

        idx = 0
        def sattr = new StringBuilder()
        root.SATTR.D.each { d ->
            sattr << (idx++ ? ',' : '') << "\"${clean(d.@ATTR.text())}\":\"${clean(d.text())}\""
        }
        nitem.json['sattr'] = sattr

        Image image = new Image('accwareid': nitem.utils.accwareid)

        root.IMG.D.each { d ->

            switch(d.@TPIMG.text()) {
                case '300':
                    image.imgs['0'] = d.text()
                    break
                case 'Front':
                    image.imgs['front'] = d.text()
                    break
                case 'Right':
                    image.imgs['right'] = d.text()
                    break
                case 'Left':
                    image.imgs['left'] = d.text()
                    break
                case 'Rear':
                    image.imgs['rear'] = d.text()
                    break
                case 'Top':
                    image.imgs['top'] = d.text()
                    break
                case 'Bottom':
                    image.imgs['bottom'] = d.text()
                    break
                case 'Manufacturer-Brochure':
                    image.pdf['brochure'] = d.text()
                    break
                case 'User-Manual':
                    image.pdf['manual'] = d.text()
                    break
            }
        }

        // try get images from bookmaker
        if(!image.imgs['front'] && !nitem.images.url1.isEmpty()) {
            image.imgs['front'] = nitem.images.url1
        }
        if(!image.imgs['right'] && !nitem.images.url2.isEmpty()) {
            image.imgs['right'] = nitem.images.url2
        }
        if(!image.imgs['left'] && !nitem.images.url3.isEmpty()) {
            image.imgs['left'] = nitem.images.url3
        }

        // set front default image
        if(!image.imgs['0'] && !nitem.images.url0.isEmpty()) {
            image.imgs['0'] = nitem.images.url0
        }
        else if(!image.imgs['0'] && image.imgs['front']) {
            image.imgs['0'] = image.imgs['front']
        }
        else if(!image.imgs['0'] && image.imgs['right']) {
            image.imgs['0'] = image.imgs['right']
        }
        else if(!image.imgs['0'] && image.imgs['left']) {
            image.imgs['0'] = image.imgs['left']
        }
        if(!image.imgs['0']) {
            image.imgs['0'] = "http://10.0.2.18/defcat/${nitem.category['categoryid']}.jpg"
        }

        //println "image=${image.imgs}"
        nitem.json.imgs = image.getJson()
        nitem.json.pics = image.getPictures()
        //nitem.json['pdf'] = image.getManual()
*/
        return ['time': System.currentTimeMillis() - start]
    }

    // Time excecution
    def benchmark = { closure ->
        def start = System.currentTimeMillis()
        closure.call()
        return System.currentTimeMillis() - start
    }

    def void doGet(HttpServletRequest request, HttpServletResponse response)    { processRequest(request, response) }
    def void doPost(HttpServletRequest request, HttpServletResponse response)   { processRequest(request, response) }
    String getServletInfo() { return "ItemsService" }

}
